// pages/edit/edit.js
var app = getApp();
const db = wx.cloud.database()
const eve = db.collection('eve')
const user = db.collection('user')
import Toast from '../../vant-weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    addr: '',
    max_num: '',
    start_time: '',
    end_time: '',
    start_time_date: '',
    end_time_date: '',
    qqgroup: '',
    qqwx: '',
    good_name: '',
    good_price: '',
    des: '',
    show_popup_start_time: false,
    show_popup_end_time: false,
    currentDate: new Date().getTime(),
    fileList: [],
    addFileList: [],
    delFileList: [],
    folder: 'uploader',
    tmpUrlArr: [],
  },

  onChange_name(event) {
    this.setData({ name: event.detail})
  },

  onChange_addr(event) {
    this.setData({ addr: event.detail})
  },

  onChange_max_num(event) {
    this.setData({ max_num: event.detail})
  },

  onChange_qqwx(event) {
    this.setData({ qqwx: event.detail})
  },

  onChange_qqgroup(event) {
    this.setData({ qqgroup: event.detail})
  },

  onChange_good_name(event) {
    this.setData({ good_name: event.detail})
  },

  onChange_good_price(event) {
    this.setData({ good_price: event.detail})
  },

  onChange_des(event) {
    this.setData({ des: event.detail})
  },

  //点击选择活动开始时间
  onClick_start_time() {
    this.setData({ show_popup_start_time: true });
  },

  //点击选择活动结束时间
  onClick_end_time() {
    this.setData({ show_popup_end_time: true });
  },

  //确认选择活动开始时间
  onConfirm_start_time(event) {
    var date = new Date(event.detail);
    this.setData({ 
      start_time: this.formateDate(date), 
      start_time_date: date, 
      show_popup_start_time: false
    });
  },

  //确认选择活动结束时间
  onConfirm_end_time(event) {
    var date = new Date(event.detail);
    this.setData({
       end_time: this.formateDate(date) ,
       end_time_date: date,
       show_popup_end_time: false
    });
  },
  //格式化时间输出
  formateDate: function (date) {
    if (date == "" || date == null) {
      return false
    }
    var y = date.getFullYear();
    var m = (Number(date.getMonth()) + 1);
    var d = date.getDate();
    var h = date.getHours();
    var mi = Number(date.getMinutes());
    if (mi<10)
      mi = '0' + mi;
    return y+"/"+m+"/"+d+"/"+h+":"+mi;
  },

  //关闭选择时间界面
  onClose_popup_start_time() {
    this.setData({ show_popup_start_time: false });
  },
  onClose_popup_end_time() {
    this.setData({ show_popup_end_time: false });
  },

  afterRead(event) {
    const file = event.detail.file[0];
    this.data.fileList.push(file);
    this.data.addFileList.push(file)
    var files = this.data.fileList;
    var addFiles = this.data.addFileList;
    this.setData({
      fileList: files ,
      addFileList: addFiles ,
    })
  },

  uploadToCloud(check_result) {
    wx.cloud.init();

    var path = this.data.folder;
    this.setData({
      path
    })
    if (this.data.addFileList.length == 0) {
      this.uploadData(check_result);
      return true;
    } else {
      var fileList = this.data.addFileList;
      var date = new Date().getTime();
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`${path}/${date}-${app.globalData.open_id}-${index}`, file));
      Promise.all(uploadTasks)
        .then(data => {
          wx.showToast({ title: '图片上传成功', icon: 'none' });
          var newFileList = data.map(item => {
            return item.fileID
          });
          console.log(newFileList);
          this.setData({ 
            tmpUrlArr: this.data.tmpUrlArr.concat(newFileList),    
          });
          this.uploadData(check_result);
          return true;
        })
        .catch(e => {
          Toast.clear();
          wx.showToast({ title: '上传失败', icon: 'none' });
          console.log(e);
          return false;
        });
    }
  },
  getImageInfo(chooseResult) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: chooseResult.url,
        success (res) {
          resolve(res.type)
        },
        fail (err) {
          console.log(err)
          reject(err)
        }
      })
    })
  },
  delCloudImage() {
    var that = this;
    if (that.data.delFileList.length<1) {
      return true;
    }
    return new Promise((resolve, reject) => {
      wx.cloud.deleteFile({
        fileList: that.data.delFileList,
        success (res) {
          console.log(res.fileList)
          return true
        },
        fail (err) {
          console.log(err)
          reject(err)
        }
      })
    })
  },
  
  async uploadFilePromise(fileName, chooseResult) {
    var type = await this.getImageInfo(chooseResult);
    console.log(chooseResult);
    return wx.cloud.uploadFile({
      cloudPath: fileName + '.' + type,
      filePath: chooseResult.url,
    });
  },

  deleteImg(event) {
    var index = event.detail.index;
    if (index<this.data.tmpUrlArr.length) {
      var delfile = this.data.delFileList;
      var newfile = this.data.fileList;
      delfile.push((newfile.splice(index,1))[0].url);
      var newtempfile = this.data.tmpUrlArr;
      newtempfile.splice(index,1);
      console.log(delfile)
      this.setData({
        fileList: newfile,
        tmpUrlArr: newtempfile,
        delFileList: delfile,
      })
    } else {
      var newfile = this.data.fileList;
      newfile.splice(index,1);
      var newtempfile = this.data.addFileList;
      newtempfile.splice(index-this.data.tmpUrlArr.length,1);
      this.setData({
        fileList: newfile,
        addFileList: newtempfile,
      })
    }
  },

  checkInput() {
    if (this.data.activity_type == 0) {
      if (this.data.name == null || this.data.name == '') {
        wx.showToast({ title: '未填写活动名称！', icon: 'none' });
        return -1;
      }
      if (this.data.addr == null || this.data.addr == '') {
        wx.showToast({ title: '未填写地点！', icon: 'none' });
        return -1;
      }
      if (this.data.max_num == null || this.data.max_num == '') {
        wx.showToast({ title: '未填写人数！', icon: 'none' });
        return -1;
      }
      if (Number.isInteger(Number(this.data.max_num)) == false) {
        wx.showToast({ title: '人数必须是纯数字！', icon: 'none' });
        return -1;
      }
      if (this.data.start_time == null || this.data.start_time == '') {
        wx.showToast({ title: '未选择开始时间！', icon: 'none' });
        return -1;
      }
      if (this.data.qqgroup == null || this.data.qqgroup == '') {
        wx.showToast({ title: '未填写QQ群号！', icon: 'none' });
        return -1;
      }
      if (Number.isInteger(Number(this.data.qqgroup)) == false) {
        wx.showToast({ title: 'QQ群号必须是纯数字！', icon: 'none' });
        return -1;
      }
      if (this.data.des == null || this.data.des == '') {
        wx.showToast({ title: '未填写简介！', icon: 'none' });
        return -1;
      }
      return 0;
    } else if (this.data.activity_type == 1) {
      if (this.data.name == null || this.data.name == '') {
        wx.showToast({ title: '未填写活动名称！', icon: 'none' });
        return -1;
        }
        if (this.data.good_name == null || this.data.good_name == '') {
          wx.showToast({ title: '未填写物品名称！', icon: 'none' });
          return -1;
        }
        if (Number.isNaN(this.data.max_num)) {
          wx.showToast({ title: '价格必须是数字！', icon: 'none' });
          return -1;
        }
        if (this.data.qqwx == null || this.data.qqwx == '') {
          wx.showToast({ title: '未填写联系方式！', icon: 'none' });
          return -1;
        }
        if (this.data.des == null || this.data.des == '') {
          wx.showToast({ title: '未填写简介！', icon: 'none' });
          return -1;
        }
        return 1;
    } else if (this.data.activity_type == 2) {
      if (this.data.name == null || this.data.name == '') {
        wx.showToast({ title: '未填写活动名称！', icon: 'none' });
        return -1;
      }
      if (this.data.addr == null || this.data.addr == '') {
        wx.showToast({ title: '未填写地点！', icon: 'none' });
        return -1;
      }
      if (this.data.good_name == null || this.data.good_name == '') {
        wx.showToast({ title: '未填写物品名称！', icon: 'none' });
        return -1;
      }
      if (this.data.qqwx == null || this.data.qqwx == '') {
        wx.showToast({ title: '未填写联系方式！', icon: 'none' });
        return -1;
      }
      if (this.data.des == null || this.data.des == '') {
        wx.showToast({ title: '未填写简介！', icon: 'none' });
        return -1;
      }
      return 2;
    }  else {
      wx.showToast({ title: '修改活动失败！', icon: 'none' });
      console.log(this.data.activity_type);
      return -1;
    }
  },

  uploadData(check_result) {
    this.delCloudImage();
    var that= this;
    wx.cloud.callFunction({
      name: 'editEvent',
      data: {
        _id: that.data.event_id,
        check_result: check_result,
        name: that.data.name,
        addr: that.data.addr,
        max_num: that.data.max_num,
        start_time_date: that.data.start_time_date,
        end_time_date: that.data.end_time_date,
        qqgroup: that.data.qqgroup,
        qqwx: that.data.qqwx,
        good_name: that.data.good_name,
        good_price: that.data.good_price,
        des: that.data.des,
        tmpUrlArr: that.data.tmpUrlArr,
      },
    }).then(res => {
      Toast.clear();
      wx.showToast({ title: '修改活动成功！', icon: 'success' });
      wx.navigateBack({});
    })
    .catch(console.error)
  },

  //按下修改按钮
  onClickButton(){
    var check_result = this.checkInput();
    if (check_result >= 0 ) {
      Toast.loading({
        duration: 0,
        mask: true,
        message: '数据提交中...',
        forbidClick: true,
        selector: '#custom-selector',
      });
      this.uploadToCloud(check_result);
      return true;
    } else {
      Toast.clear();
      wx.showToast({ title: '修改活动失败！', icon: 'none' });
      return false;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var event_id = options.event_id;
    db.collection('eve').doc(event_id).get({
      success: function(res) {
        console.log(res.data)
        var type = Number(res.data.type)-1;
        that.setData({
          event_id: event_id,
          activity_type: type,
          name: res.data.name,
          addr: res.data.addr,
          max_num: res.data.max_num,
          start_time: that.formateDate(res.data.start_time),
          end_time: that.formateDate(res.data.end_time),
          start_time_date: res.data.start_time,
          end_time_date: res.data.end_time,
          qqgroup: res.data.qqgroup,
          qqwx: res.data.qqwx,
          good_name: res.data.good_name,
          good_price: res.data.good_price,
          des: res.data.des,
          show_popup_start_time: false,
          show_popup_end_time: false,
          folder: 'uploader',
          tmpUrlArr: res.data.pic,
        })
        var tempFileList = that.data.tmpUrlArr.map(item => ({
          url: item
        }));
        that.setData({
          fileList: tempFileList,
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})